# -*- coding: utf-8 -*-
__author__ = 'liubei'

from mongoengine import *
import time
import db_engine
import db

host = db_engine.host

articleHtml = '''
    <!DOCTYPE html><html>  <head>    <meta charset='utf-8'>    <meta http-equiv='X-UA-Compatible' content='IE=edge'>    <meta name='viewport' content='width=device-width, initial-scale=1'>    <meta name='description' content=''>    <meta name='author' content=''>    <link href='http://v3.bootcss.com/dist/css/bootstrap.min.css' rel='stylesheet'>  </head>  <body style='background:rgba(255, 255, 255, 0)'>    <div class='container' style='margin-top:20px'>     <h4>%s</h4>          <p>%s   %s</p>    <image src='%s' style='width:100%%'>    <p style='margin-top:30px'>%s</p><p style='margin-top:10px;font-size:small;font-style:italic;text-align:right;'>%s</p>   </div>  </body></html>
 '''


class Topic(DynamicDocument):
    title = StringField(required=True)
    des = StringField(required=True)
    image = StringField(required=True)
    sentIndex = IntField(required=True)
    # createDate = IntField(required=True, default=int(time.time()))


class LongMsgStrategy(DynamicDocument):
    day = IntField(required=True)
    msg_no = IntField(required=True)
    isSmoke = IntField(required=True)


class QuizStratergy(DynamicDocument):
    day = IntField(required=True)
    quiz_nos = ListField(required=True)
    isSmoke = IntField(required=True)


class Article(DynamicDocument):
    title = StringField(required=True)
    des = StringField(required=True)
    source = StringField(required=True)
    image = StringField(required=True)
    content = StringField(required=True)
    topicId = StringField(required=True)
    articleIndex = StringField(required=True)
    artileCatalog = StringField(required=True)
    publishDate = IntField()
    createDate = IntField(required=True, default=int(time.time()))


class Question(DynamicDocument):
    topicId = StringField(required=True)
    title = StringField(required=True)
    type = IntField(default=1)
    correctAnswer = StringField(required=True)
    choices = ListField(required=True)
    createDate = IntField(required=True, default=int(time.time()))
    articleIndex = StringField(required=True)


class QuestionRecord(DynamicDocument):
    meta = {'collection': "questionRecord"}
    userPhone = StringField(required=True)
    createDate = IntField(required=True, default=int(time.time()))


class ArticleStatus(DynamicDocument):
    isRead = IntField(required=True)
    articleId = StringField(required=True)
    userPhone = StringField(required=True)
    createDate = IntField(required=True, default=int(time.time()))


def isReadByTopicId(userPhone, topicId):
    connect('az', host=host)
    articles = db.queryArticleListByTopicId(topicId, userPhone)['articles']
    isRead = ''
    for article in articles:
        status = ArticleStatus.objects(articleId=str(article['uid']), userPhone=userPhone)
        if status.count() == 0:
            isRead += '0'
        elif status.count() > 0 and status[0].isRead == 1:
            isRead += '1'
    if '0' in isRead:
        return 0
    else:
        return 1


def isReadByArticleId(userPhone, articleId):
    connect('az', host=host)
    status = ArticleStatus.objects(articleId=articleId, userPhone=userPhone)
    if status.count() > 0 and status[0].isRead == 1:
        return 1
    return 0


def updateReadByArticleId(userPhone, articleId):
    connect('az', host=host)
    status = ArticleStatus.objects(articleId=articleId, userPhone=userPhone)
    if status.count() == 0:
        status = ArticleStatus(articleId=articleId, userPhone=userPhone, isRead=1)
        status.save()


def queryQuestionStrategy(day, isSmoke):
    connect('az', host=host)
    msgStrategys = QuizStratergy.objects(day__lte=day, day__gt=day - 14, isSmoke=isSmoke)
    return msgStrategys


def queryLongMsgStrategy(day, isSmoke):
    connect('az', host=host)
    msgStrategys = LongMsgStrategy.objects(day__lte=day, isSmoke=isSmoke)
    return msgStrategys


if __name__ == "__main__":
    connect('az', host=host)

    statin = Topic(title='他丁类药物知识',
                   des='什么是他汀类药物？他汀类(Statins)也称3羟基3甲基戊二酰辅酶A（HMG-CoA）还原酶抑制剂，具有竞争性抑制细胞内胆固醇合成；世界上临床应用他汀类药物已有20多年的历史，主要用于降低血脂和心血管疾病的预防。',
                   image='http://jenkins.qiniudn.com/statin1.png')
    statinId = str(statin.save().id)
    statinArticle1 = Article(title='什么是他汀类药物？',
                             des='什么是他汀类药物？他汀类(Statins)也称3羟基3甲基戊二酰辅酶A（HMG-CoA）还原酶抑制剂，具有竞争性抑制细胞内胆固醇合成；世界上临床应用他汀类药物已有20多年的历史，主要用于降低血脂和心血管疾病的预防。',
                             image='http://jenkins.qiniudn.com/statin1.png', topicId=statinId)
    statinArticle1.content = articleHtml % (statinArticle1.title, '', '', statinArticle1.image, statinArticle1.des, statinArticle1.source)
    statinArticle1.save()

    statinArticle2 = Article(title='他汀类药物的适应症是什么呢？',
                             des='他汀类药物的适应症是什么呢？主要用于治疗血脂异常，还用于防治冠心病、治疗急性冠脉综合征、冠状动脉搭桥术和介入术后等。他汀类药物能显著降低血清总胆固醇（TC）和低密度脂蛋白胆固醇（LDL-C）。',
                             image='http://jenkins.qiniudn.com/statin2.png', topicId=statinId)
    statinArticle2.content = articleHtml % (statinArticle2.title, '', '', statinArticle2.image, statinArticle2.des, statinArticle2.source)
    statinArticle2.save()

    statinArticle3 = Article(title='为什么要应用他汀类药物呢？',
                             des='为什么要应用他汀类药物呢？因为血脂异常是动脉粥样硬化心血管疾病的主要原因之一，他汀类药物可以减少心血管疾病的死亡风险，心血管疾病治疗指南亦明确将他汀类作为治疗的基本药物之一。',
                             image='http://jenkins.qiniudn.com/statin3.png', topicId=statinId)
    statinArticle3.content = articleHtml % (statinArticle3.title, '', '', statinArticle3.image, statinArticle3.des, statinArticle3.source)
    statinArticle3.save()

    statinQuestion1 = Question(title='关于他汀类药物描述哪项是错的？', topicId=statinId, correctAnswer='C')
    statinQuestion1.choices = [{'label': 'A', 'des': '他汀类药物可以抑制胆固醇合成'}, {'label': 'B', 'des': '他汀类用于临床已有20多年了'},
                               {'label': 'C', 'des': '他汀类主要用于止血，防治血栓形成'}, {'label': 'D', 'des': '他汀类有效降脂，可预防心血管疾病'}]
    statinQuestion1.save()

    statinQuestion2 = Question(title='关于他汀类的适应症哪项正确？', topicId=statinId, correctAnswer='A')
    statinQuestion2.choices = [{'label': 'A', 'des': '治疗血脂异常，防治冠心病'}, {'label': 'B', 'des': '不能用于冠状动脉搭桥术后'},
                               {'label': 'C', 'des': '不能用于冠心病介入治疗后'}, {'label': 'D', 'des': '有效降低血总胆固醇，不能降低LDL-C'}]
    statinQuestion2.save()

    statinQuestion3 = Question(title='为什么要应用他汀类药物？理由有哪些？（多选）', topicId=statinId, correctAnswer='ABC')
    statinQuestion3.choices = [{'label': 'A', 'des': '有效降脂改善动脉粥样硬化'}, {'label': 'B', 'des': '减少心血管疾病的死亡风险'},
                               {'label': 'C', 'des': '国内外心血管治疗指南均明确推荐'}, {'label': 'D', 'des': '应用他汀类药物降血脂没有依据'}]
    statinQuestion3.save()

    cholesterol = Topic(title='胆固醇相关知识介绍',
                        des='血清总胆固醇（TC）的主要营养成份是饱和脂肪酸及膳食胆固醇，TC异常升高与长期过量饱和脂肪酸（>7％/日）和胆固醇（>200mg/日）密切相关。肥胖、年龄、妇女绝经等因素也起作用。',
                        image='http://jenkins.qiniudn.com/tc1.png')
    cholesterolId = str(cholesterol.save().id)

    cholesterolArticle1 = Article(title='血清总胆固醇（TC）',
                                  des='血清总胆固醇（TC）的主要营养成份是饱和脂肪酸及膳食胆固醇，TC异常升高与长期过量饱和脂肪酸（>7％/日）和胆固醇（>200mg/日）密切相关。肥胖、年龄、妇女绝经等因素也起作用。',
                                  image='http://jenkins.qiniudn.com/tc1.png', topicId=cholesterolId)
    cholesterolArticle1.content = articleHtml % (
    cholesterolArticle1.title, '', '', cholesterolArticle1.image, cholesterolArticle1.des, cholesterolArticle1.source)
    cholesterolArticle1.save()

    cholesterolArticle2 = Article(title='血脂分类',
                                  des='医院将血脂异常分为4类，包括：①高胆固醇血症，血清总胆固醇（TC）水平增高；②高甘油三脂血症（TG）；③混合型高脂血症，TC和TG水平均高；④低高低密度脂蛋白血症，血清HDL-C水平减少',
                                  image='http://jenkins.qiniudn.com/tc2.png', topicId=cholesterolId)
    cholesterolArticle2.content = articleHtml % (
    cholesterolArticle2.title, '', '', cholesterolArticle2.image, cholesterolArticle2.des, cholesterolArticle2.source)
    cholesterolArticle2.save()

    cholesterolArticle3 = Article(title='健康成人血清总胆固醇',
                                  des='健康成人血清总胆固醇（TC）小于200mg/dl，如果为201～239mg/dl则称为边缘升高，大于240～289mg/dl为轻度高胆固醇血症，大于290mg/dl以上为重度高胆固醇血症。TC小于240mg/dl开始接受TLC（治疗性生活方式干预），TC大于240mg/dl以上要采用TLC加他汀类药物治疗。',
                                  image='http://jenkins.qiniudn.com/tc3.png', topicId=cholesterolId)
    cholesterolArticle3.content = articleHtml % (
    cholesterolArticle3.title, '', '', cholesterolArticle3.image, cholesterolArticle3.des, cholesterolArticle3.source)
    cholesterolArticle3.save()

    # diseases = Topic(title='其他心脑血管疾病知识介绍', des='')

    diet = Topic(title='饮食', des='饮食习惯是影响血总胆固醇（TC）的主要因素之一，长期高胆固醇、高饱和脂肪酸摄入可造成TC升高。其它影响TC的因素还包括年龄与性别，以及遗传因素。',
                 image='http://jenkins.qiniudn.com/diet1.png')
    print str(diet.save().id)
